package scau.mis4.chanyulin.tools;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by cyl on 2018/1/2.
 * 定时任务类
 */
public class PeriodTask {

    private Runnable runnableObj;
    private TimerTask timerTask;
    private Timer timer = new Timer();
    private double delay = 0.0;      // 默认没有延迟时间
    private double period = 1.0;     // 默认1秒执行一次

    public PeriodTask(Runnable runnableObj) {
        this.runnableObj = runnableObj;
        timerTask = new TimerTask() {
            @Override
            public void run() {
                getRunnableObj().run();
            }
        };
        timer = new Timer();
    }

    /**
     * 创建一个新的定时任务并执行
     * @param runnableObj
     * @param delay
     * @param period
     */
    public static void createAndSchedule(Runnable runnableObj, double delay, double period) {
        PeriodTask task = new PeriodTask(runnableObj);
        task.schedule(delay, period);
    }

    public static void createAndSchedule(Runnable runnableObj, double period) {
        createAndSchedule(runnableObj, 0, period);
    }

    /**
     * getters and setters...
     */
    public Runnable getRunnableObj() {
        return runnableObj;
    }

    public void setRunnableObj(Runnable runnableObj) {
        this.runnableObj = runnableObj;
    }

    public double getDelay() {
        return delay;
    }

    public void setDelay(double delay) {
        this.delay = delay;
    }

    public double getPeriod() {
        return period;
    }

    public void setPeriod(double period) {
        this.period = period;
    }

    /**
     * 执行任务
     */
    public void schedule() {
        timer.schedule(this.timerTask, Math.round(this.delay * 1000), Math.round(this.period * 1000));
    }

    public void schedule(double period) {
        this.setPeriod(period);
        this.schedule();
    }

    public void schedule(double delay, double period) {
        this.setDelay(delay);
        this.setPeriod(period);
        this.schedule();
    }

    /**
     * 取消任务
     */
    public void cancel() {
        this.timerTask.cancel();
        this.timer.cancel();
    }

}
